package com.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.config.RedisLockServer;

/**
 * @author Fang Ruichuan
 * @date 2022-09-02 13:17
 */
@RestController
@RequestMapping("/redis")
public class TestController {

    @Autowired
    private RedisLockServer  redisLockServer;

    @GetMapping("/lock")
    public String reduceSku() throws InterruptedException {
        String value = UUID.randomUUID().toString();
        // value值任意即可，设置自动过期时间为10s
        boolean lock = redisLockServer.setLock("key", value, 10, TimeUnit.SECONDS);
        if (lock) {
            // 当前key没有锁，加锁成功，执行数据库查询
            System.out.println("======>加锁成功");
            // 模拟延时8s
            TimeUnit.SECONDS.sleep(8);
            redisLockServer.deleteLock("key", value);
        } else {
            System.out.println("======>加锁失败，等待重试...");
        }
        return "操作成功";
    }
}
